package cn.com.se.sharepictrue.activity;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;


import com.loopj.android.http.PersistentCookieStore;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.se.sharepictrue.R;
import cn.com.se.sharepictrue.application.Data;
import cn.com.se.sharepictrue.bean.UserInfoBean;
import cn.com.se.sharepictrue.business.CallBack;
import cn.com.se.sharepictrue.business.ImageLoader;
import cn.com.se.sharepictrue.business.NetworkResponse;
import cn.com.se.sharepictrue.business.ShareApi;
import cn.com.se.sharepictrue.fragment.ShareListFragment;
import cn.com.se.sharepictrue.utils.DoubleClickExit;
import cn.com.se.sharepictrue.utils.StringUtils;
import cn.com.se.sharepictrue.utils.ToastUtils;
import de.hdodenhof.circleimageview.CircleImageView;

public class HomeActivity extends ActionBarActivity {

    private static final int HOME_LOGIN = 1;
    @Bind(R.id.tb_home_toolbar)
    Toolbar tbHomeToolbar;
    @Bind(R.id.fl_home_content)
    FrameLayout flHomeContent;
    @Bind(R.id.btn_drawer_login)
    Button btnDrawerLogin;
    @Bind(R.id.iv_drawer_avatar)
    CircleImageView ivDrawerAvatar;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.tv_drawer_name)
    TextView mTvDrawerName;
    @Bind(R.id.tv_drawer_logout)
    TextView mTvSignOut;
    @Bind(R.id.tv_drawer_publish)
    TextView mTvPublish;
    @Bind(R.id.tv_drawer_collection)
    TextView mTvCollection;
    @Bind(R.id.tv_drawer_follower)
    TextView mTvFollower;
    @Bind(R.id.tv_drawer_following)
    TextView mTvFollowing;
    @Bind(R.id.tv_drawer_like)
    TextView mTvLike;
    @Bind(R.id.tv_drawer_comment)
    TextView mTvComment;
    @Bind(R.id.tv_drawer_share)
    TextView mTvShare;

    private ActionBarDrawerToggle drawerToggle;

    private ShareListFragment mShareListFragment;
    private FragmentManager mFragmentManager;

    private SearchView searchView;
    private UserInfoBean mUserInfo;
    private DoubleClickExit mDoubleClickExit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        mFragmentManager = getFragmentManager();
        mDoubleClickExit = new DoubleClickExit(this);
        initToolbar();
        initDrawerLayout();
        initHomePage();
        getUserInfo();
    }

    private void getUserInfo() {
        ShareApi.userInfo(HomeActivity.this, new CallBack<NetworkResponse<UserInfoBean>>() {
            @Override
            public void onFail() {
                //ToastUtils.show(MineInfoActivity.this, errorResponse.getError());
                ToastUtils.show(HomeActivity.this, "获取用户数据失败");
            }

            @Override
            public void onResponse(NetworkResponse<UserInfoBean> response) {
                if (!response.isStatus()) {
                    //ToastUtils.show(HomeActivity.this, response.getError());
                    signOutComplete();
                } else {
                    ((Data) (HomeActivity.this.getApplication())).setUserInfo(response.getData());
                    mUserInfo = ((Data) (HomeActivity.this.getApplication())).getUserInfo();
                    setUserInfo();
                }
            }
        });
    }

    private void setUserInfo() {
        if (!((Data) getApplication()).isLogin())
            return;
        setDrawerItemVisibility(View.VISIBLE);
        if (mUserInfo.getPortraitImage() != null)
            ivDrawerAvatar.setImageBitmap(mUserInfo.getPortraitImage());
        else if (!StringUtils.isEmpty(mUserInfo.getPortrait()) && mUserInfo.getPortrait().length() > 26)
            ImageLoader.getInstance(HomeActivity.this).load(ivDrawerAvatar, mUserInfo.getPortrait());
        else
            ivDrawerAvatar.setImageResource(R.mipmap.bg_drawer);
        mTvDrawerName.setText(mUserInfo.getUserName());
        btnDrawerLogin.setVisibility(View.INVISIBLE);
    }

    private void signOut() {
        ShareApi.logOut(HomeActivity.this, new CallBack<NetworkResponse<String>>(HomeActivity.this, "正在登出...") {
            @Override
            public void onFail() {
                ToastUtils.show(HomeActivity.this, "登出失败");
            }

            @Override
            public void onResponse(NetworkResponse<String> response) {
                if (!response.isStatus())
                    ToastUtils.show(HomeActivity.this, response.getError());
                else {
                    signOutComplete();
                }
            }
        });


    }

    private void signOutComplete() {
        setDrawerItemVisibility(View.GONE);
        if (mUserInfo != null)
            mUserInfo.clearUserInfo();
        ivDrawerAvatar.setImageResource(R.mipmap.bg_drawer);
        btnDrawerLogin.setVisibility(View.VISIBLE);
        PersistentCookieStore myCookieStore = new PersistentCookieStore(HomeActivity.this);
        myCookieStore.clear();
        mShareListFragment.initData();
    }

    private void setDrawerItemVisibility(int visibility) {
        ivDrawerAvatar.setVisibility(visibility);
        mTvSignOut.setVisibility(visibility);
        mTvDrawerName.setVisibility(visibility);
        mTvCollection.setVisibility(visibility);
        mTvFollower.setVisibility(visibility);
        mTvFollowing.setVisibility(visibility);
        mTvPublish.setVisibility(visibility);
        mTvShare.setVisibility(visibility);
        mTvLike.setVisibility(visibility);
        mTvComment.setVisibility(visibility);
    }

    private void initToolbar() {
        setSupportActionBar(tbHomeToolbar);
        tbHomeToolbar.setTitleTextColor(Color.WHITE);
        tbHomeToolbar.setNavigationIcon(R.mipmap.ic_menu);
    }

    private void initHomePage() {
        mShareListFragment = ShareListFragment.getNewInstance();
        mFragmentManager.beginTransaction()
                .replace(R.id.fl_home_content, mShareListFragment)
                .commit();
    }

    private void initDrawerLayout() {
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, tbHomeToolbar, R.string.app_name, R.string.app_name);

        drawerLayout.setDrawerListener(drawerToggle);
    }

    @OnClick({R.id.tv_drawer_share, R.id.btn_drawer_login, R.id.tv_drawer_publish,
            R.id.tv_drawer_following, R.id.tv_drawer_follower, R.id.iv_drawer_avatar,
            R.id.tv_drawer_setting, R.id.tv_drawer_collection, R.id.tv_drawer_like, R.id.tv_drawer_comment, R.id.tv_drawer_logout})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_drawer_share://分享
                doShare();
                break;
            case R.id.btn_drawer_login:// 登录/注册
                Intent LoginIntent = new Intent(this, LoginActivity.class);
                startActivityForResult(LoginIntent, HOME_LOGIN);
                break;
            case R.id.tv_drawer_publish:// 我的发表
                Intent PersonIntent = new Intent(this, PersonalHomepageActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(PersonalHomepageActivity.HOMEPAGE_USERID, mUserInfo.getUserID());
                bundle.putString(PersonalHomepageActivity.HOMEPAGE_USERNAME, mUserInfo.getUserName());
                bundle.putString(PersonalHomepageActivity.HOMEPGE_USERPIC, mUserInfo.getPortrait());
                bundle.putString(PersonalHomepageActivity.HOMEPAGE_KEY, PersonalHomepageActivity.HOMEPAGE_ME);
                PersonIntent.putExtras(bundle);
                startActivity(PersonIntent);
                break;
            case R.id.iv_drawer_avatar:// 点击头像
                Intent MineInfoIntent = new Intent(this, MineInfoActivity.class);
                startActivityForResult(MineInfoIntent, 0);
                break;
            case R.id.tv_drawer_following: //我的关注
                Intent concernIntent = new Intent(this, ConcernActivity.class);
                concernIntent.putExtra(ConcernActivity.CONCERN_WHAT_TITLE,
                        getResources().getString(R.string.concern_following_title));
                startActivity(concernIntent);
                break;
            case R.id.tv_drawer_follower: //我的粉丝
                Intent followerIntent = new Intent(this, ConcernActivity.class);
                followerIntent.putExtra(ConcernActivity.CONCERN_WHAT_TITLE,
                        getResources().getString(R.string.concern_follower_title));
                startActivity(followerIntent);
                break;
            case R.id.tv_drawer_setting:// 设置
                Intent settingIntent = new Intent(this, SettingActivity.class);
                startActivity(settingIntent);
                break;
            case R.id.tv_drawer_collection://我的收藏
                Intent collectionIntent = new Intent(this, MineCollectionActivity.class);
                startActivity(collectionIntent);
                break;
            case R.id.tv_drawer_like://我的点赞
                Intent likeIntent = new Intent(this, MineLikeActivity.class);
                startActivity(likeIntent);
                break;
            case R.id.tv_drawer_comment://我的评论
                Intent commentIntent = new Intent(this, MineCommentActivity.class);
                startActivity(commentIntent);
                break;
            case R.id.tv_drawer_logout:
                signOut();
                break;
        }
        if (drawerLayout.isDrawerOpen(GravityCompat.START))
            drawerLayout.closeDrawer(GravityCompat.START);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            drawerLayout.openDrawer(GravityCompat.START);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                drawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }else {
                return mDoubleClickExit.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        switch (item.getItemId()) {
            case android.R.id.home:
                drawerLayout.openDrawer(GravityCompat.START);
                return true;
//            case R.id.action_home_search:
//                showSearchWindow(item);
//                return true;
            case R.id.action_home_rank:
                showRankWindow();
                return true;
            case R.id.action_home_share:
                doShare();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void doShare() {
        Intent intent = new Intent(this, PublishActivity.class);
        startActivity(intent);
    }

    private void showRankWindow() {
        Intent intent = new Intent(this, RankActivity.class);
        startActivity(intent);
    }

//    private void showSearchWindow(MenuItem item) {
//        // 一个自定义的布局，作为显示的内容
//        final View contentView = LayoutInflater.from(this).inflate(
//                R.layout.layout_search_popup_window, null);
//        initPopupView(contentView);
//
//
//        PopupWindow popupWindow = new PopupWindow(contentView,
//                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//
//        popupWindow.setTouchable(true);
//
//        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
//                return false;
//                // 这里如果返回true的话，touch事件将被拦截
//                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
//            }
//        });
//        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//
//            @Override
//            public void onDismiss() {
//                // 设置背景颜色变暗
//                WindowManager.LayoutParams lp = getWindow().getAttributes();
//                lp.alpha = 1.0f;
//                getWindow().setAttributes(lp);
//            }
//        });
//        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
//        // 我觉得这里是API的一个bug
//        popupWindow.setBackgroundDrawable(getResources().getDrawable(
//                R.drawable.shape_search_popup));
//
//        // 设置好参数之后再show
//        popupWindow.showAtLocation(tbHomeToolbar, Gravity.NO_GRAVITY, (int) tbHomeToolbar.getX(), (int) tbHomeToolbar.getY() + SystemUtils.getStatusBarHeight(this));
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.alpha = 0.7f;
//        getWindow().setAttributes(lp);
//    }
//
//    private void initPopupView(final View contentView) {
//        // 设置按钮的点击事件
//        TextView search = (TextView) contentView.findViewById(R.id.tv_search_popup_search);
//        final EditText input = (EditText) contentView.findViewById(R.id.et_search_popup_input);
//        search.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                Snackbar.make(tbHomeToolbar, input.getText().toString(), Snackbar.LENGTH_SHORT).show();
//                doSearch();
//            }
//        });
//        input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    doSearch();
//                    return true;
//                }
//                return false;
//            }
//        });
//    }

    private void doSearch(String query) {
        hideKeyboard();
        Intent intent = new Intent();
        intent.setClass(HomeActivity.this, SearchActivity.class);
        intent.putExtra("search", query);
        startActivity(intent);
    }

    private void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                    hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_home, menu);
        MenuItem menuItem = menu.findItem(R.id.action_home_search);//在菜单中找到对应控件的item
        searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        initSearchView(menuItem);
        return true;
    }

    private void initSearchView(final MenuItem menuItem) {
        MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                return true;
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!StringUtils.isEmpty(query)) {
                    Log.e("xxxxxxxxxxxxxxxxxx", "do  search");
                    doSearch(query);
                    MenuItemCompat.collapseActionView(menuItem);
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return true;
            }
        });
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mUserInfo = ((Data) getApplicationContext()).getUserInfo();
        setUserInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (((Data) getApplicationContext()).isLogin())
            return;
        getUserInfo();
    }

}
